const clientMap = require("../service/WebSocketService").clientMap;
const UserService = require("../service/UserService");
const LoginInfo = require("../statics/LoginInfo");

const _ = require("underscore");
/**
 * 主界面路由
 * @param app - express对象
 */
const addLoginRoute = function(app){
	/**
	 * 验证用户是否已登录, 转到登录界面或主界面
	 */
	app.get(["/", "/index", "login"], (request, response) => {
		//首先从session当中获取, 验证该用户是否在当前会话已登录
		if("loginUser" in request.session) {
			response.render("main",{
				user:request.session.loginUser
			});
		} else if(request.cookies.username && request.cookies.password){
			//然后从cookie中获取, 验证该用户是否已经记住账号密码
			let user = {
				username : request.cookies.username,
				password : request.cookies.password
			};
			let successCb = function(userNow){
				request.session.loginUser = userNow;
				response.render("main",{user:userNow});
			};
			let failedCb = function(){
				response.render("login",LoginInfo.NONE);
			};
			UserService.checkUser(user, true, successCb, failedCb);
		} else {
			response.render("login",LoginInfo.NONE);
		}
	});
	/**
	 * 用户登录
	 */
	app.post("/login_in", (request, response) => {
		const user = request.body.user;
		if(clientMap.has(user.username)) {
			//用户已登录
			response.render("login", LoginInfo.LOGINED);
			return;
		}
		const failedCb = function(){
			//用户验证失败的回调函数
			response.render("login", LoginInfo.FAILED);
		};
		const successCb = function(userNow){
			request.session.loginUser = userNow;
			if(request.body.remember_me) {
				//记住用户登录状态, 写入cookie
				_.each(user, (value, key) => {
					response.cookie(key, value, require("../statics/LoadConfig").cookie);
				});
			}
			response.redirect("/index");
		};
		UserService.checkUser(user, false, successCb, failedCb);
	});
	/**
	 * 用户注销
	 */
	app.get("/logout", (request, response) => {
		if("loginUser" in request.session) {
			_.each(request.session.loginUser, (value, key) => {
				response.clearCookie(key);
			});
			delete request.session.loginUser;
		}
		response.render("login",LoginInfo.NONE);
	});
};
module.exports = addLoginRoute;
